import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
    三个售票员同时卖30张票
    企业级代码:
        1.在高内聚低耦合的前提下通过线程操作资源类
 */
public class SaleTicketDemo {
    public static void main(String[] args) {
        Ticket ticket=new Ticket();
        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                while (true){
                    if (!ticket.isEmpty()){
                        ticket.sale();
                    }else {
                        break;
                    }
                }
            },String.valueOf(i+1)).start();
        }
    }
}
class Ticket{
    private int number=30;
    private Lock lock=new ReentrantLock();

    public void sale(){
        lock.lock();
        try {
            if(number>0){
                System.out.println(Thread.currentThread().getName()+"卖了一张票,剩余:"+--number);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public boolean isEmpty(){
        lock.lock();
        try {
            if(number>0){
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return true;
    }
}
